package com.yx.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.common.vo.Result;
import com.yx.sys.entity.Followed;
import com.yx.sys.entity.Post;
import com.yx.sys.entity.Role;
import com.yx.sys.entity.User;
import com.yx.sys.mapper.UserMapper;
import com.yx.sys.service.IFollowedService;
import com.yx.sys.service.IPostService;
import com.yx.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息 前端控制器
 * controller 通过调用service来完成业务逻辑
 * </p>
 *
 * @author yx
 * @since 2023-02-14
 */
@Api(tags = {"用户接口列表"})
@RestController
@RequestMapping("/user")
//@CrossOrigin 跨域处理，局部的
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IPostService postService;
    @Autowired
    private IFollowedService followedService;
//    查询所有用户数据
    @ApiOperation("查询所有用户数据")
    @GetMapping("/all")
    public Result<List<User>> getAllUser(){
        List<User> list = userService.list();
        return Result.success(list,"查询所有用户数据成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Map<String,Object>> login(@RequestBody User user){
        System.out.println(user);
        Map<String,Object> data = userService.login(user);
        if(data != null){
            return Result.success(data);
        }
        return Result.fail(20002,"用户名或密码错误");
    }

//    根据token获取头像 昵称 权限等身份信息
    @ApiOperation("获取登录用户信息")
    @GetMapping("/info")
    public Result<Map<String,Object>> getUserInfo(@RequestParam("token") String token){
//        根据token获取用户信息，redis
        Map<String,Object> data = userService.getUserInfo(token);
        System.out.println("用户信息："+data);
        if(data!=null){
            return Result.success(data);
        }
        return Result.fail(20003,"登录信息无效，请重新登录");
    }

//    退出登录
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token){
        userService.logout(token);
        return Result.success();
    }

//    根据用户名 邮箱 页码 页数查询用户列表

    @ApiOperation("条件查找用户")
    @GetMapping("/list")
    public Result<Map<String,Object>> getUserList(@RequestParam(value = "username",required = false) String username,
                                                  @RequestParam(value = "uEmail",required = false) String uEmail,
                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(username),User::getUsername,username);
        wrapper.like(StringUtils.hasLength(uEmail),User::getUEmail,uEmail);
        wrapper.orderByDesc(User::getUId);
        Page<User> page = new Page<>(pageNo,pageSize);
        userService.page(page,wrapper);
        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }

//    新增用户 注册用户
    @ApiOperation("注册用户")
    @PostMapping
    public Result<String> addUser(@RequestBody User user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        System.out.println("新增用户"+user);
        String s = userService.addUser(user);
        return Result.success(s);
    }

//    修改用户
    @ApiOperation("修改用户")
    @PutMapping
    public Result<?> updateUser(@RequestBody User user){
        System.out.println(user);
        user.setPassword(null);
        userService.updateUser(user);
        return Result.success("修改用户成功");
    }

    @ApiOperation("id查询用户信息")
    @GetMapping("/{uId}")
    public Result<User> getUserById(@PathVariable("uId") Integer uId){
        User user = userService.getUserById(uId);
        return Result.success(user);
    }
    @ApiOperation("昵称模糊查询用户信息")
    @GetMapping("/fuzzyNickname")
    public Result<List<?>> getUserByNickname(String nickname){
        List<?> list = userService.getUserByNickname(nickname);
        System.out.println(list);
        return Result.success(list);
    }
//    根据用户id查询用户信息

    @ApiOperation("id查询用户")
    @GetMapping("/userMes")
    public Result<Map<String, Object>> getUserByuId(@PathParam("uId") Integer uId){
        User user = userService.getById(uId);
        Map<String, Object> data = new HashMap<>();
        data.put("uId",user.getUId());
        data.put("nickname",user.getNickname());
        data.put("uAvatar",user.getUAvatar());
        data.put("uEmail",user.getUEmail());
        data.put("status",user.getStatus());
        data.put("username",user.getUsername());
        data.put("fansNum",user.getFansNum());
        QueryWrapper<Post> wrapper = new QueryWrapper<>();
        wrapper.eq("uId",user.getUId());
        long count = postService.count(wrapper);
        data.put("postMesTotal",count);
        System.out.println(data);
        return Result.success(data);
    }

//    根据用户id删除用户

    @ApiOperation("id删除用户")
    @DeleteMapping("/{uId}")
    public Result<User> deleteUserById(@PathVariable("uId") Integer uId){
        userService.deleteUserById(uId);
        return Result.success("删除用户成功");
    }

//    根据用户名称模糊查询

//    根据邮箱查询用户是否存在
    @ApiOperation("邮箱验证用户是否存在")
    @GetMapping("/email")
    public Result<?> getUserByEmail(@RequestParam(value = "uEmail") String uEmail){
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("uEmail",uEmail);
//        User user = userService.getOne(wrapper);
        userService.emailVerification(uEmail);
        return Result.success(null,"成功");
    }

//    用户关注

    @ApiOperation("关注用户")
    @PutMapping("/follow")
    public Result<?> updateFollow(@RequestBody Map<String,Integer> params){
//        查询该用户是否已被关注
        LambdaQueryWrapper<Followed> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Followed::getFollowedId,params.get("followedId")).eq(Followed::getuId,params.get("uId"));
        if(followedService.getOne(wrapper)==null){
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUId,params.get("followedId")).set(User::getFansNum,params.get("fansNum")+1);
            Boolean flag = userService.update(updateWrapper);
            if(flag){
                followedService.insertFollow(params.get("followedId"),params.get("uId"));
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("isFollow",true);
        map.put("fansNum",userService.getById(params.get("followedId")).getFansNum());
        System.out.println(map);
        return Result.success(map,"关注成功");
    }

//    取消关注

    @ApiOperation("取消关注")
    @PutMapping("/cancelFollow")
    public Result<?> cancelFollow(@RequestBody Map<String,Integer> params){
//        粉丝数-1
        //查询该用户是否已被关注
//        System.out.println(params);
//        System.out.println(params.get("uId"));
        Boolean isCancel = null;
        FollowedController followedController = new FollowedController();
        LambdaQueryWrapper<Followed> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Followed::getFollowedId,params.get("followedId")).eq(Followed::getuId,params.get("uId"));
        Followed followed = followedService.getOne(wrapper);
        System.out.println(followed);
        if(followed!=null){
//            followedController = new FollowedController();
//            isCancel = followedController.delFollow(followed.getfId());
            isCancel = followedService.cancelFollow(followed.getfId());
            System.out.println(isCancel);
            Boolean flag = null;
//            if(isCancel){
//                LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
//                updateWrapper.eq(User::getuId,params.get("followedId")).set(User::getFansNum,params.get("fansNum")-1);
//                flag = userService.update(updateWrapper);
//                System.out.println(flag);
//            }
        }
        return Result.success(isCancel,"取消关注成功");
    }

//    根据uId查询用户信息
//    注销用户

    @ApiOperation("id注销用户")
    @PutMapping("/{uId}")
    public Result<?> deleteUser(@PathVariable("uId") Integer uId){
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUId,uId).set(User::getDeleted,1);
        userService.update(updateWrapper);
        return Result.success("删除成功");
    }

    @ApiOperation("验证注册账号是否存在")
    @GetMapping("/username")
    public Result<?> selectUsername(String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User one = userService.getOne(wrapper);
        if(one!=null){
            return Result.success("该用户已存在");
        }else{
            return Result.success(null);
        }
    }


    @ApiOperation("自行注册账号")
    @PostMapping("/register")
    public Result<?> registerUser(@RequestBody Map<String,?> user){
        System.out.println(user);
        userService.registerUser(user);
        return Result.success("注册完成，请进入登录页面登录账号");
    }

    @ApiOperation("重置密码")
    @PostMapping("/reset")
    public Result<?> resetPassword(@RequestBody Map<String,?> user){
        System.out.println("重置密码"+user);
        String pwd = userService.resetPassword(user);
        return Result.success(pwd,"重置密码成功，新密码请查收");
    }

    @ApiOperation("验证用户名和密码")
    @GetMapping("/verifyPwd")
    public Result<?> verifyPwd(String username,String oldPwd){
        System.out.println(username);
        System.out.println(oldPwd);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userService.getOne(wrapper);
//        passwordEncoder.matches(需要验证的不加密密码，数据库里的原始密码)
        boolean matches = passwordEncoder.matches(oldPwd,user.getPassword());
        System.out.println(matches);
        if(matches){
            return Result.success(1,"密码验证通过");
        }else{
            return Result.success(0,"密码错误，或可退出登录前重置密码");
        }
    }
    @ApiOperation("修改密码")
    @PutMapping("/revisePwd")
    public Result<?> revisePwd(@RequestBody Map<String,String> params){
        System.out.println(params);
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(User::getUsername,params.get("username").toString()).eq(User::getPassword,passwordEncoder.encode(params.get("newPwd").toString()));
        updateWrapper.eq(User::getUsername,params.get("username"));
        updateWrapper.set(User::getPassword,passwordEncoder.encode(params.get("newPwd")));
        userService.update(updateWrapper);
        return Result.success("密码修改成功");
    }


}
